import { useEffect, useRef } from "react";

/**
 * 实现一个useTimeout Hooks
 * useTimeout 是可以在函数式组件中，处理 setTimeout 计时器函数
 */
export type Callback = () => void;

function useTimeout(callback: Callback, delay: number) {
  const memorizedCallback = useRef<Callback>();

  useEffect(() => {
    memorizedCallback.current = callback;
  }, [callback]);

  useEffect(() => {
    const timer = setTimeout(() => {
      if (memorizedCallback.current !== undefined) {
        memorizedCallback.current();
      }
    }, delay);

    return () => {
      clearTimeout(timer);
    };
  }, [delay]);
}

export default useTimeout;
